package facade

import (
	"context"
	"fmt"
	"gitee.com/flycash/ai-gateway-demo/internal/domain"
	"gitee.com/flycash/ai-gateway-demo/internal/service/llm"
)

type Service struct {
	platformMap     map[string]llm.Service
	defaultPlatform llm.Service
}

func NewService(llmMap map[string]llm.Service, defaultPlatform llm.Service) *Service {
	return &Service{
		platformMap:     llmMap,
		defaultPlatform: defaultPlatform,
	}
}

func (s *Service) SyncInvoke(ctx context.Context, req domain.SyncRequest) (domain.SyncResponse, error) {
	platformFunc, err := s.getService(req.Model.Provider)
	if err != nil {
		return domain.SyncResponse{}, err
	}
	return platformFunc.SyncInvoke(ctx, req)
}

func (s *Service) StreamInvoke(ctx context.Context, req domain.SyncRequest) (chan domain.StreamEvent, error) {
	platformFunc, err := s.getService(req.Model.Provider)
	if err != nil {
		return nil, err
	}
	return platformFunc.StreamInvoke(ctx, req)
}

func (s *Service) AsyncInvoke(ctx context.Context, req domain.AsyncRequest) (domain.AsyncResponse, error) {
	platformFunc, err := s.getService(req.Req.Model.Provider)
	if err != nil {
		return domain.AsyncResponse{}, err
	}
	return platformFunc.AsyncInvoke(ctx, req)
}

func (s *Service) getService(provider string) (llm.Service, error) {
	if provider == "" {
		return s.defaultPlatform, nil
	}
	platform, ok := s.platformMap[provider]
	if !ok {
		return nil, fmt.Errorf("未知大模型平台: %s", provider)
	}
	return platform, nil
}

func (s *Service) Healthy(ctx context.Context) bool{
	return true
}